package lk.service;

import lk.dao.LoginDao;
import lk.exception.ResponseCodeContants;
import lk.exception.RestfulRecord;
import lk.pojo.UserInfo;
import lk.util.SessionUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @Description: 登录业务层实现类
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginDao loginDao;


    @Override
    public Object login(String loginName, String password) {
        //普通用户 取配置权限
        UserInfo userInfo = loginDao.findUserByLoginAndPassword(loginName, password, false);
        if (userInfo != null) {
            return getUserInfo(userInfo, false);
        }
        return new RestfulRecord(ResponseCodeContants.ERROR_CODE, "账号错误，请重新登录！", false);
    }

    @Override
    public int addUser(UserInfo user) {
        UserInfo u1 = loginDao.findUserByLoginName(user.getLoginName());
        UserInfo u2 = loginDao.findUserByTel(user.getTel());
        if (u1 != null || u2 != null) {
            return 0;
        }
        String id = UUID.randomUUID().toString();
        System.out.println("id===" + id);
        user.setUserId(id);
        System.out.println("user=====" + user.getUserId());
        user.setPassword(user.getLoginName() + "*123");
        user.setPasswordUpdateTime(new Date());
        return loginDao.addUser(user);
    }

    @Override
    public UserInfo findUserByLoginName(String loginName) {
        return loginDao.findUserByLoginName(loginName);
    }


    /**
     * 根据标志位判断是否为管理员登录
     *
     * @param flag true=管理员登录；false=普通用户登录
     * @return
     */
    private Object getUserInfo(UserInfo userInfo, boolean flag) {
        //普通用户
        userInfo.setManager(false);
        SessionUtil.setSessionAttribute("user", userInfo);
        System.out.println("--------普通用户登录-----------");
        System.out.println(userInfo);
        return new RestfulRecord(ResponseCodeContants.SUCCESS_CODE, "登录成功！", userInfo);

    }


}
